<template>
  <view class="m-checkbox-view">
    <view
      v-for="(option, index) in options"
      :key="index"
      class="checkbox-item-view"
      :class="option.checked?'theme-border theme-color':'gray-border'"
      @tap="toggle(option)"
    >
      <view class="checkbox-info-view text-ellipsis-view">
        {{ option.text }}
      </view>
      <icons src="/static/icon/checkedtag.svg" :props="{fill: `,${$clr}`}" size="28" v-show="option.checked"
             style="position: absolute; top: -1rpx; right: -1rpx; z-index: 2;"/>
    </view>
  </view>
</template>
<script setup>
import {computed} from 'vue'

const props = defineProps({
  modelValue: {
    required: true,
    type: Array,
    default: () => []
  },
  options: {
    required: true,
    type: [Array, Object],
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const options = computed(() => {
  const ops = []
  if (props.options instanceof Array) {
    ops.push(...props.options)
  } else {
    for (const key in props.options) {
      ops.push({
        value: key,
        text: props.options[key],
      })
    }
  }
  const a = ops.map(i => {
    return {
      ...i,
      checked: props.modelValue && props.modelValue.includes(i.value)
    }
  })
  return a
})

function toggle(option) {
  option.checked = !option.checked
  emit('update:modelValue', options.value.filter(i => i.checked).map(i => i.value))
}
</script>
<style lang="scss">
.m-checkbox-view {
  background-color: white;
  display: flex;
  flex-wrap: wrap;

  .checkbox-item-view {
    height: 2em;
    display: flex;
    position: relative;
    border-radius: 8rpx;
    margin: 7rpx;

    .checkbox-info-view {
      padding: 0 20rpx;
      text-align: center;
      line-height: 2em;
    }
  }
}
</style>
